package singleton;

/**
 * @program: thread
 * @description:懒汉式
 * @author: gongj
 * @Description: TODO
 * @create: 2020-07-11 21:25
 **/
public class SingletonTest2 {
    // 加上 volatile 关键字，解决 instance = new SingletonTest2() 处的指令重排问题
    private volatile static SingletonTest2 singleton = null;

    private SingletonTest2(){
        System.out.println("无参构造方法执行");
    }
    public  static SingletonTest2 getSingleton(){
        if(singleton == null){
            synchronized (SingletonTest2.class){
                if(singleton == null){
                    return  singleton = new SingletonTest2();
                }
            }
        }
        return singleton;
    }

    public  static void main(String[] args) {
        for (int i = 0; i < 60; i++) {
            new Thread(()->{
                System.out.println(SingletonTest2.getSingleton());
            }).start();
        }
    }
}
